//
//  AudioRecord.m
//  Test_aacRecord
//
//  Created by DING FENG on 12/9/14.
//  Copyright (c) 2014 DING FENG. All rights reserved.
//

#import "AudioRecord.h"
#import <AVFoundation/AVFoundation.h>
//#import "NSFileManager+plus.h"
//#import "meterLevellabel.h"
//#import "MeterLevelWaveView.h"


@interface AudioRecord()
{
    UIView  *_recordView;
//    meterLevellabel  *_metelevelLabel;
//    MeterLevelWaveView *_meterLevelWaveView;
    AVAudioRecorder *recorder;
    NSURL *_tmpFileUrl;
    CADisplayLink  *_displayLink;
    NSTimer *_displayTimer;
    RecordIconView  *_recordIconView;
    UIView   *_deleteIconView;
    NSTimer   *showTimer;
    
    int   secendsCount;
    BOOL  timeOut_60s;
    
}
@property  (nonatomic,weak)  UIViewController  *fromController;

@end

@implementation AudioRecord
@synthesize recordView=_recordView;
@synthesize tmpFileUrl=_tmpFileUrl;
@synthesize recordIconView=_recordIconView;
- (id)init
{
    self = [super init];
    if (self)
    {        
        self.voiceRecordView = [[FZVoiceRecordView alloc] initWithFrame:CGRectMake(30, 20, 100, 100)];
        _recordView = [[UIView  alloc]  init];
        _recordView.frame = CGRectMake(0, 0, [UIScreen  mainScreen].bounds.size.width, [UIScreen  mainScreen].bounds.size.height-50);
        _recordView.backgroundColor = [UIColor colorWithRed:20./255 green:20./255 blue:20./255 alpha:0.7];
//        _metelevelLabel =[[meterLevellabel  alloc]  initWithFrame:CGRectMake(0, 0, 320, 44)];
//        _metelevelLabel.text = @"meterlevel";
//        _metelevelLabel.backgroundColor  = [UIColor   grayColor];
        NSString *docsDir = CachesDirectory;
        self.audioPath = [docsDir stringByAppendingPathComponent:@"tmpAudioRecordFileUrl.aac"];
        _tmpFileUrl = [NSURL fileURLWithPath:self.audioPath];
        
        [self removeDeleteIconAndAddMicIcon];
    }
    return self;
}

-(AudioRecord *)initFromViewController:(UIViewController  *)fromController{
    AudioRecord *arv = [[AudioRecord  alloc ]  init];
    arv.fromController=fromController;
    return arv;
}
-(void)recordBegin{
//    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
//    [recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
//    
//    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
//    [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
//    
//    [recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
//    [recordSetting setValue:[NSNumber numberWithBool: NO] forKey:AVLinearPCMIsBigEndianKey];

    NSDictionary *recordSetting = [NSDictionary dictionaryWithObjectsAndKeys:
                                    [NSNumber numberWithInt: kAudioFormatMPEG4AAC], AVFormatIDKey,
                                    [NSNumber numberWithFloat:8000.0], AVSampleRateKey,
                                    [NSNumber numberWithInt: 2], AVNumberOfChannelsKey,
                                    nil];
    [self recordBeginWithSettings:recordSetting];
}

-(void)recordBeginWithRongyunSetting{
    NSString *docsDir = CachesDirectory;
    self.audioPath = [docsDir stringByAppendingPathComponent:@"tmpAudioRecordFileUrl.caf"];
    _tmpFileUrl = [NSURL fileURLWithPath:self.audioPath];
//    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
//    [recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey];
//    
//    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
//    [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
//    
//    [recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
//    [recordSetting setValue:[NSNumber numberWithBool: NO] forKey:AVLinearPCMIsBigEndianKey];
//
    NSDictionary *recordSetting = @{
                                     AVFormatIDKey : @(kAudioFormatLinearPCM),
                                     AVSampleRateKey : @8000.00f,
                                     AVNumberOfChannelsKey : @1,
                                     AVLinearPCMBitDepthKey : @16,
                                     AVLinearPCMIsNonInterleaved : @NO,
                                     AVLinearPCMIsFloatKey : @NO,
                                     AVLinearPCMIsBigEndianKey : @NO
                                     };
    [self recordBeginWithSettings:recordSetting];
}


-(void)recordBeginWithSettings:(NSDictionary*)settings{
    self.voiceRecordView.state = LCChatRecorderMetersAlertViewStateRecording;
    [self.voiceRecordView show];
    timeOut_60s = NO;
    if(showTimer){
        [showTimer  invalidate];
        showTimer = nil;
    }
    secendsCount = 0;
    
    NSTimeInterval timeInterval =1.0 ;
    //定时器
    showTimer = [NSTimer scheduledTimerWithTimeInterval:timeInterval
                                                 target:self
                                               selector:@selector(handleTimer:)
                                               userInfo:nil
                                                repeats:YES];
    
    [showTimer setFireDate:[NSDate distantFuture]];
    NSLog(@"recordBegin");
    NSString  *path = [_tmpFileUrl   path];
    NSError *error;
    if ([[NSFileManager defaultManager] isDeletableFileAtPath:path]) {
        BOOL success = [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        if (!success) {
            NSLog(@"Error removing file at path: %@", path);
        }
    }
    _displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayLinkRefresh)];
    _displayLink.frameInterval = 7;
    [_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    
    NSError *recorderError;
    recorder = [[AVAudioRecorder alloc] initWithURL:_tmpFileUrl settings:settings error:&recorderError];
    
    if(recorderError){
        NSLog(@"Error recorder: %@", recorderError);
    }
    
//    [recorder prepareToRecord];
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryRecord error:nil];
    [session setActive:YES error:nil];
    [recorder setMeteringEnabled:YES];
    [recorder record];
    [showTimer setFireDate:[NSDate date]];
    
    [self removeDeleteIconAndAddMicIcon];
}

-(void)recordCancel{
    if(showTimer){
        [showTimer  invalidate];
        showTimer = nil;
    }
    secendsCount = 0;
    
    
    self.voiceRecordView.state = LCChatRecorderMetersAlertViewStateCancelTips;
    
    //invalidate and free the display link
    [_displayLink invalidate];
    _displayLink = nil;
    NSLog(@"recordCancel");
    [_recordView  removeFromSuperview];
    [self.voiceRecordView dismiss];
    [recorder stop];
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];

//    int flags = AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation;
//    [session setActive:NO withFlags:flags error:nil];
    
    
}
-(void)recordComplete{
    if (timeOut_60s) {
        return;
    }
    
    if(showTimer){
        [showTimer  invalidate];
        showTimer = nil;
    }
    [_displayLink invalidate];
    _displayLink = nil;
    
    [_recordView  removeFromSuperview];
    [recorder stop];
    
    if(secendsCount < 1) {
        [self showTooShortSign];

    } else {
        AVAudioSession *session = [AVAudioSession sharedInstance];
        [session setCategory:AVAudioSessionCategoryPlayback error:nil];

//        int flags = AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation;
//        [session setActive:NO withFlags:flags error:nil];
//        
        AVURLAsset* audioAsset = [AVURLAsset URLAssetWithURL:_tmpFileUrl options:nil];
        CMTime audioDuration = audioAsset.duration;
        float audioDurationSeconds = CMTimeGetSeconds(audioDuration);
        
        if (audioDurationSeconds >= 59) {
            audioDurationSeconds =60;
        }
        
        NSLog(@"audioDurationSeconds  %f",audioDurationSeconds);
        BOOL   result;
        result = NO;
        if (audioDurationSeconds >= 1.f) {
            [self.voiceRecordView dismiss];
            result = YES;
        } else if (audioDurationSeconds > 60.f) {
          
        } else {
            [self showTooShortSign];
        }
        
        self.mediaLenth = [NSString  stringWithFormat:@"%.1f",audioDurationSeconds];
        
        if (self.completeBlock) {
            self.completeBlock(result,_tmpFileUrl);
        }
    }
    //invalidate and free the display link
}


- (NSInteger)timeLenght {
    return secendsCount;
}

-(void)displayLinkRefresh{
    
    [recorder updateMeters];
    recorder.meteringEnabled = YES;//fix the long decay time   ( thx to http://mattlogandev.blogspot.jp/2013/06/easy-fix-for-slow-level-decay-time-with.html
    float level;                // The linear 0.0 .. 1.0 value we need.
    
    float minDecibels = -80.0f; // Or use -60dB, which I measured in a silent room.
    
    float decibels = [recorder averagePowerForChannel:0];
    
    if (decibels < minDecibels) {
        level = 0.0f;
    } else if (decibels >= 0.0f) {
        level = 1.0f;
    } else {
        float   root            = 2.0f;
        
        float   minAmp          = powf(10.0f, 0.05f * minDecibels);
        
        float   inverseAmpRange = 1.0f / (1.0f - minAmp);
        
        float   amp             = powf(10.0f, 0.05f * decibels);
        
        float   adjAmp          = (amp - minAmp) * inverseAmpRange;
        
        level = powf(adjAmp, 1.0f / root);
    }
    
    //NSLog(@"平均值 %f", level * 120);
    
    //double peakPowerForChannel =[recorder peakPowerForChannel:0];
    double peakPowerForChannel = [recorder averagePowerForChannel:0];
    [self.voiceRecordView setAudioMeterProgress:level * 120];
    //听觉线性和分贝之间需要转换
    /*
     The range is from -160 dB to 0 dB. You probably want to display it in a meter that goes from -90 dB to 0 dB. Displaying it as decibels is actually more useful than as a linear audio level, because the decibels are a logarithmic scale, which means that it more closely approximates how loud we perceive a sound.
     That said, you can use this to convert from decibels to linear:
     linear = pow (10, decibels / 20);
     and the reverse:
     decibels = log10 (linear) * 20;
     The range for the above decibels is negative infinity to zero, and for linear is 0.0 to 1.0. When the linear value is 0.0, that is -inf dB; linear at 1.0 is 0 dB.
     */
    float linear = pow (10, peakPowerForChannel / 20);
    float peaker = [recorder peakPowerForChannel:0];
    peaker = fmaxf(peaker, 0.0);
    peaker = fminf(peaker, 1.0);
    
//    _metelevelLabel.lineMeterLevel = linear;
//    [_metelevelLabel  setNeedsDisplay];
//    
//    [_meterLevelWaveView   updateRecordMeterLevel:linear ];
    [_recordIconView  updateRecordMeterLevel:linear];
}



-(void)removeMicIconAndAddDeleteIcon{
    
    self.recordStatus = FZAudioRecordStatusMoveToCancel;
    self.voiceRecordView.state = LCChatRecorderMetersAlertViewStateCancelTips;
    [_deleteIconView  removeFromSuperview];
    [_recordIconView  removeFromSuperview];
    
    _deleteIconView = [[UIView  alloc]  initWithFrame:CGRectMake(0, 0, 328/2., 328/2.)];
    _deleteIconView.backgroundColor = [UIColor   clearColor];
    _deleteIconView.center  = CGPointMake(_deleteIconView.frame.size.width/2.,_deleteIconView.frame.size.width/2.);
    UIImageView  *deleteIcon = [[UIImageView  alloc]   initWithFrame:CGRectMake(0, 0, 170/2., 170/2.)];
    deleteIcon.image = [UIImage  imageNamed:@"删除灰@2x.png"];
    deleteIcon.center = CGPointMake(_recordView.frame.size.width/2., _recordView.frame.size.width/2.);
    UIImageView  *textHint = [[UIImageView  alloc]  initWithFrame:CGRectMake(164/2., 164/2., 130, 25)];
    textHint.image = [UIImage  imageNamed:@"上滑取消发送-删除@2x.png"];
    textHint.center = CGPointMake(_recordView.frame.size.width/2., _recordView.frame.size.width/2.+80);
    [_deleteIconView  addSubview:textHint];
    [_deleteIconView  addSubview:deleteIcon];
    [_recordView  addSubview:_deleteIconView];
    _deleteIconView.alpha = 0;
    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        _deleteIconView.alpha = 1;
    } completion:^(BOOL finished)
     {
     }];
    
}

-(void)removeDeleteIconAndAddMicIcon{
    
    self.recordStatus = FZAudioRecordStatusRecording;
    self.voiceRecordView.state = LCChatRecorderMetersAlertViewStateRecording;
    [_deleteIconView  removeFromSuperview];
    [_recordIconView  removeFromSuperview];
    _recordIconView = [[RecordIconView  alloc]  initWithFrame:CGRectMake(0, 0, 328/2., 328/2.)];
    _recordIconView.backgroundColor = [UIColor   clearColor];
    _recordIconView.center  = CGPointMake(_recordView.frame.size.width/2.,_recordView.frame.size.width/2.);
    
    UIImageView  *micIcon = [[UIImageView  alloc]   initWithFrame:CGRectMake(0, 0, 170/2., 170/2.)];
    micIcon.image = [UIImage  imageNamed:@"麦克风@2x.png"];
    micIcon.center = CGPointMake(_recordIconView.frame.size.width/2., _recordIconView.frame.size.width/2.);
    UIImageView  *textHint = [[UIImageView  alloc]  initWithFrame:CGRectMake(164/2., 164/2., 130, 25)];
    textHint.image = [UIImage  imageNamed:@"上滑取消发送@2x.png"];
    textHint.center = CGPointMake(_recordIconView.frame.size.width/2., _recordIconView.frame.size.width/2.+80);
    [_recordIconView  addSubview:textHint];
    [_recordIconView  addSubview:micIcon];
    _recordIconView.iconImageView =micIcon;
    _recordIconView.countNumLabel.alpha = 0;
    
    
    [_recordView  addSubview:_recordIconView];
    
    _recordIconView.alpha = 0;
    [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        _recordIconView.alpha = 1;
    } completion:^(BOOL finished)
     {
     }];
    
}

-(void)showTooShortSign {
    
    self.voiceRecordView.state = LCChatRecorderMetersAlertViewStateWarning;
    secendsCount = 0;
    double delayInSeconds = 1.f;
    ESWeakSelf
    dispatch_time_t delayInNanoSeconds = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(delayInNanoSeconds, dispatch_get_main_queue(), ^(void){
        ESStrongSelf
        [_self.voiceRecordView dismiss];
    });
}
-(void)handleTimer:(id)sender{
    secendsCount ++;
    self.voiceRecordView.duration = secendsCount;
    if (secendsCount >= 60 * 5) {
        [self  recordComplete];
        timeOut_60s = YES;
        if(showTimer){
            [showTimer  invalidate];
            showTimer = nil;
        }
    }
}
-(void)dealloc{
    NSLog(@"dealloc   dealloc");
}

-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
    
//    int flags = AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation;
//    [session setActive:NO withFlags:flags error:nil];
//    
}
@end
